package com.example.myapplication.tools;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Environment;
import android.widget.Toast;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


public class FileUtils {
	private String SDPATH;

	public String getSDPATH() {
		return SDPATH;
	}
	public FileUtils() {
		//得到当前外部存储设备的目录
		// /SDCARD
		SDPATH = Environment.getExternalStorageDirectory() + "/";
	}
	public  String formatFileSize(File file){
		if(file.isDirectory())return "";
		double size=file.length();
		String strSize;
		DecimalFormat df = new DecimalFormat("#.00");  
		if(size<1024){
			strSize =df.format(size) + "B";//B
		}else if(size <1048576){
			strSize =df.format(size/1024) + "K";//K
		}else if(size <1073741824){
			strSize =df.format(size/1048576) + "M";//M
		}else{
			strSize =df.format(size/1073741824) + "G";//G
		}
		return strSize;
	}
	public static String formatFileSize(double size){
		String strSize;
		DecimalFormat df = new DecimalFormat("#.00");
		if(size<1024){
			strSize =df.format(size) + "B";//B
		}else if(size <1048576){
			strSize =df.format(size/1024) + "K";//K
		}else if(size <1073741824){
			strSize =df.format(size/1048576) + "M";//M
		}else{
			strSize =df.format(size/1073741824) + "G";//G
		}
		return strSize;
	}
	
	public String foramtFileTime(File file){
		Date dt=new Date(file.lastModified());
		SimpleDateFormat dateFormat=new SimpleDateFormat("yyyy年MM月dd日");
		return dateFormat.format(dt);
	}
	public String getFileExtName(String fileName){
		int index=fileName.lastIndexOf(".");
		if(index==-1)return "";
		return fileName.substring(index);	
	}
	
	/**
	 * 保留两位小数
	 * @param d
	 * @return
	 */
	public static String formatDouble(double d){
		DecimalFormat df = new DecimalFormat("#.00");
		return df.format(d * 100);
	}
	
	public static int formatInteger(double d){
		int end = (int)(d * 100);
		return end;
	}
	
	/**
	 
	* 打开文件
	 
	* @param file
	 
	*/
	 
	public void openFile(File file,Activity activity){
	 
		Intent intent = new Intent();
		 
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		 
		//设置intent的Action属性
		 
		intent.setAction(Intent.ACTION_VIEW);
		 
		//获取文件file的MIME类型
		 
		String type = getMIMEType(file);
		
		if(type.equals("*/*")){
			Toast.makeText(activity, "未知文件类型！", Toast.LENGTH_SHORT).show();
			return;
		}
		
		//设置intent的data和Type属性。
		 
		intent.setDataAndType(Uri.fromFile(file), type);
		 
		//跳转
		 
		activity.startActivity(intent); 

	}
	 

	/**
	 
	* 根据文件后缀名获得对应的MIME类型。
	 
	* @param file
	 
	*/
	 
	private String getMIMEType(File file) {
	 

		String type="*/*";
		 
		String fName = file.getName();
		 
		//获取后缀名前的分隔符"."在fName中的位置。
		 
		int dotIndex = fName.lastIndexOf(".");
		 
		if(dotIndex < 0){
		 
		return type;
		 
		}
		 
		/* 获取文件的后缀名 */
		 
		String end=fName.substring(dotIndex,fName.length()).toLowerCase();
		 
		if(end=="")return type;
		 
		//在MIME和文件类型的匹配表中找到对应的MIME类型。
		 
		for(int i=0;i<MIME_MapTable.length;i++){ 
		 
		if(end.equals(MIME_MapTable[i][0]))
		 
		type = MIME_MapTable[i][1];
		 
		} 
		return type;
	 
	}
	private final String[][] MIME_MapTable={
			{".3gp", "video/3gpp"},
			{".apk", "application/vnd.android.package-archive"},
			{".asf", "video/x-ms-asf"},
			{".avi", "video/x-msvideo"},
			{".bin", "application/octet-stream"},
			{".bmp", "image/bmp"},
			{".c", "text/plain"},
			{".class", "application/octet-stream"},
			{".conf", "text/plain"},
			{".cpp", "text/plain"},
			{".doc", "application/msword"},
			{".docx", "application/vnd.openxmlformats-officedocument.wordprocessingml.document"},
			{".xls", "application/vnd.ms-excel"}, 
			{".xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"},
			{".exe", "application/octet-stream"},
			{".gif", "image/gif"},
			{".gtar", "application/x-gtar"},
			{".gz", "application/x-gzip"},
			{".h", "text/plain"},
			{".htm", "text/html"},
			{".html", "text/html"},
			{".jar", "application/java-archive"},
			{".java", "text/plain"},
			{".jpeg", "image/jpeg"},
			{".jpg", "image/jpeg"},
			{".js", "application/x-javascript"},
			{".log", "text/plain"},
			{".m3u", "audio/x-mpegurl"},
			{".m4a", "audio/mp4a-latm"},
			{".m4b", "audio/mp4a-latm"},
			{".m4p", "audio/mp4a-latm"},
			{".m4u", "video/vnd.mpegurl"},
			{".m4v", "video/x-m4v"}, 
			{".mov", "video/quicktime"},
			{".mp2", "audio/x-mpeg"},
			{".mp3", "audio/x-mpeg"},
			{".mp4", "video/mp4"},
			{".mpc", "application/vnd.mpohun.certificate"}, 
			{".mpe", "video/mpeg"}, 
			{".mpeg", "video/mpeg"}, 
			{".mpg", "video/mpeg"}, 
			{".mpg4", "video/mp4"}, 
			{".mpga", "audio/mpeg"},
			{".msg", "application/vnd.ms-outlook"},
			{".ogg", "audio/ogg"},
			{".pdf", "application/pdf"},
			{".png", "image/png"},
			{".pps", "application/vnd.ms-powerpoint"},
			{".ppt", "application/vnd.ms-powerpoint"},
			{".pptx", "application/vnd.openxmlformats-officedocument.presentationml.presentation"},
			{".prop", "text/plain"},
			{".rc", "text/plain"},
			{".rmvb", "audio/x-pn-realaudio"},
			{".rtf", "application/rtf"},
			{".sh", "text/plain"},
			{".tar", "application/x-tar"}, 
			{".tgz", "application/x-compressed"}, 
			{".txt", "text/plain"},
			{".wav", "audio/x-wav"},
			{".wma", "audio/x-ms-wma"},
			{".wmv", "audio/x-ms-wmv"},
			{".wps", "application/vnd.ms-works"},
			{".xml", "text/plain"},
			{".z", "application/x-compress"},
			{".zip", "application/x-zip-compressed"},
			{"", "*/*"} 
			};
	
	/**
	 * 以行为单位读取文件，常用于读面向行的格式化文件
	 * 
	 * @param file 文件名
	 */
	public static String readFileByLines(File file) {
		StringBuffer sb = new StringBuffer();
//		File file = new File(fileName);
		BufferedReader reader = null;
		try {
			reader = new BufferedReader(new FileReader(file));
			String tempString = null;
			int line = 1;
			// 一次读入一行，直到读入null为文件结束
			while ((tempString = reader.readLine()) != null) {
				// 显示行号
				//System.out.println("line " + line + ": " + tempString);
				sb.append(tempString);
				line++;
			}
			reader.close();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (reader != null) {
				try {
					reader.close();
				} catch (IOException e1) {
				}
			}
		}
		return sb.toString();
	}
	
	/**
	 * 把字符串写入文件
	 * @param theString
	 * @param filePath
	 * @param fileName
	 */
	
	public static void writeFile(String theString,String filePath,String fileName) {
		File file = new File(filePath, fileName);
		if(file!=null){
			file.deleteOnExit();
		}
		FileOutputStream fos = null;
		try {
			file.createNewFile();
			fos = new FileOutputStream(file);
			fos.write(theString.getBytes());
			fos.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	
	public static boolean isFile(String filePath){
		if(filePath==null||filePath.length()==0){
			return false;
		}
		File f = new File(filePath);
		if(f!=null&&f.isFile()){
			return true;
		}
		return false;
	}
	/**
	 * 删除指定文件夹下所有文件
	 * 
	 * @param path
	 *            文件夹完整绝对路径
	 * @return
	 * @return
	 */
	public boolean delAllFile(String path) {
		boolean bea = false;
		File file = new File(path);
		if (!file.exists()) {
			return bea;
		}
		if (!file.isDirectory()) {
			return bea;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				delFolder(path + "/" + tempList[i]);// 再删除空文件
				bea = true;
			}
		}
		return bea;
	}
	/**
	 * 删除指定文件夹下所有文件    exception是例外路径
	 * @param path
	 * @return
	 * @return
	 */
	public boolean delAllFile(String path,List<String> exception) {
		boolean bea = false;
		File file = new File(path);
		if (!file.exists()) {
			return bea;
		}
		if (!file.isDirectory()) {
			return bea;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			boolean isException = false;
			for(int listI = 0; listI < exception.size() ; listI ++){
				if(temp.getPath().contains(exception.get(listI))){
					isException = true;
					continue;
				}
			}
			if(isException){
				continue;
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				delFolder(path + "/" + tempList[i]);// 再删除空文件
				bea = true;
			}
		}
		return bea;
	}
	public boolean delAllFile(String path,String exception) {
		boolean bea = false;
		File file = new File(path);
		if (!file.exists()) {
			return bea;
		}
		if (!file.isDirectory()) {
			return bea;
		}
		String[] tempList = file.list();
		File temp = null;
		for (int i = 0; i < tempList.length; i++) {
			if (path.endsWith(File.separator)) {
				temp = new File(path + tempList[i]);
			} else {
				temp = new File(path + File.separator + tempList[i]);
			}
			if(temp.getPath().contains(exception)){
				continue;
			}
			if (temp.isFile()) {
				temp.delete();
			}
			if (temp.isDirectory()) {
				delAllFile(path + "/" + tempList[i]);// 先删除文件夹里面的文件
				delFolder(path + "/" + tempList[i]);// 再删除空文件
				bea = true;
			}
		}
		return bea;
	}
	/**
	 * 删除文件
	 * 
	 * @param folderPath
	 *            文件夹完整绝对路径
	 * @return
	 */
	public void delFolder(String folderPath) {
		try {
			delAllFile(folderPath); // 删除完里面所有内容
			String filePath = folderPath;
			filePath = filePath.toString();
			File myFilePath = new File(filePath);
			myFilePath.delete(); // 删除空文件夹
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	/**
	 * createAssets to pad
	 * @param assetDir
	 * @param dir
	 */
	public void createAssets(Context mContext,String assetDir,String dir){
        String[] files;
         try{
             files = mContext.getResources().getAssets().list(assetDir);
         }
         catch (IOException e1){
             return;
         }
         File mWorkingPath = new File(dir);
         if(!mWorkingPath.exists()){
             if(!mWorkingPath.mkdirs()){

             }
         }
         for(int i = 0; i < files.length; i++){
             try{
                 String fileName = files[i];
                 //we make sure file name not contains '.' to be a folder.
                 if(!fileName.contains(".")){
                     if(0==assetDir.length()){
                    	 createAssets(mContext,fileName,dir+fileName+"/");
                     }else{
                    	 createAssets(mContext,assetDir+"/"+fileName,dir+fileName+"/");
                     }
                     continue;
                 }
                 File outFile = new File(mWorkingPath, fileName);
                 if(outFile.exists())
                     outFile.delete();
                 InputStream in =null;
                 if(0!=assetDir.length())
                     in = mContext.getAssets().open(assetDir+"/"+fileName);
                 else
                     in = mContext.getAssets().open(fileName);
                 OutputStream out = new FileOutputStream(outFile);
                 byte[] buf = new byte[1024];
                 int len;
                 while ((len = in.read(buf)) > 0){
                     out.write(buf, 0, len);
                 }
                 in.close();
                 out.close();
             }
             catch (FileNotFoundException e){
                 e.printStackTrace();
             }
             catch (IOException e){
                 e.printStackTrace();
             }
        }
}
	
	public static void DrawableToFile(Drawable drawable,File f){
		File parentFile = f.getParentFile();
		if(!parentFile.exists()){
			parentFile.mkdirs();
		}
		Bitmap bitmap = ((BitmapDrawable)drawable).getBitmap();
		FileOutputStream fop = null;
		try {
			fop=new FileOutputStream(f);
			bitmap.compress(Bitmap.CompressFormat.PNG, 100, fop);
			fop.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
			
	}
}